package com.test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

/**
 * poi word工具类
 */
public class POIWordUtil {

    public final static String CHECK_BOX_PT = "\\$\\{(.+?)@";

    /**
     * 解析参数
     * 
     * @param document
     * @param prefixStr
     * @param pattern
     * @param params
     */
    public static void parseDocumentParams(XWPFDocument document, String prefixStr, String pattern,
            Set<String> allPrams) {
        // 解析文本参数
        parseTextParams(document, prefixStr, pattern, allPrams);
        // 解析表格参数
        parseTableParams(document, prefixStr, pattern, allPrams);

    }

    public static void parseTextParams(XWPFDocument document, String prefixStr, String pattern, Set<String> allPrams) {
        // 获取段落集合
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            // 判断此段落时候需要进行替换
            String text = paragraph.getText();
            if (StringUtils.isNotBlank(text) && text.contains(prefixStr)) {
                List<String> params = StringReplaceUtil.parseParams(pattern, text);
                allPrams.addAll(params);
            }
        }
    }

    public static void parseTableParams(XWPFDocument document, String prefixStr, String pattern, Set<String> allPrams) {
        // 获取表格对象集合
        List<XWPFTable> tables = document.getTables();
        for (int i = 0; i < tables.size(); i++) {
            // 只处理行数大于等于2的表格，且不循环表头
            XWPFTable table = tables.get(i);
            if (table.getRows().size() > 0) {
                // 判断表格内容是否可以替换
                String cellText = table.getText();
                if (StringUtils.isNotBlank(cellText) && cellText.contains(prefixStr)) {
                    List<XWPFTableRow> rows = table.getRows();
                    // 遍历表格,并替换模板
                    parseEachTableParams(rows, prefixStr, pattern, allPrams);
                }
            }
        }
    }

    public static void parseEachTableParams(List<XWPFTableRow> rows, String prefixStr, String pattern,
            Set<String> allPrams) {
        for (XWPFTableRow row : rows) {
            List<XWPFTableCell> cells = row.getTableCells();
            for (XWPFTableCell cell : cells) {
                // 判断单元格内容是否可以替换
                String cellText = cell.getText();
                if (StringUtils.isNotBlank(cellText) && cellText.contains(prefixStr)) {
                    List<String> params = StringReplaceUtil.parseParams(pattern, cellText);
                    allPrams.addAll(params);
                }
            }
        }
    }

    /**
     * 替换内容
     *
     * @param textMap 需要替换的信息集合
     */
    public static void replaceWord(XWPFDocument document, String prefixStr, Map<String, String> textMap,
            boolean isSymbol) {
        // 解析替换文本段落对象
        changeText(document, textMap, prefixStr, isSymbol);
        // 解析替换表格对象
        changeTable(document, textMap, prefixStr, isSymbol);

    }

    /**
     * 替换段落文本
     *
     * @param document docx解析对象
     * @param textMap  需要替换的信息集合
     */
    public static void changeText(XWPFDocument document, Map<String, String> textMap, String prefixStr,
            boolean isSymbol) {
        // 获取段落集合
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            // 判断此段落时候需要进行替换
            String text = paragraph.getText();
            if (StringUtils.isNotBlank(text) && text.contains(prefixStr)) {
                if (isSymbol) {
                    replaceSymbol(textMap, paragraph, prefixStr);
                } else {
                    replaceText(textMap, paragraph);
                }
            }
        }
    }

    /**
     * 替换表格对象方法
     *
     * @param document docx解析对象
     * @param textMap  需要替换的信息集合
     */
    public static void changeTable(XWPFDocument document, Map<String, String> textMap, String prefixStr,
            boolean isSymbol) {
        // 获取表格对象集合
        List<XWPFTable> tables = document.getTables();
        for (int i = 0; i < tables.size(); i++) {
            // 只处理行数大于等于2的表格，且不循环表头
            XWPFTable table = tables.get(i);
            if (table.getRows().size() > 0) {
                // 判断表格内容是否可以替换
                String cellText = table.getText();
                if (StringUtils.isNotBlank(cellText) && cellText.contains(prefixStr)) {
                    List<XWPFTableRow> rows = table.getRows();
                    // 遍历表格,并替换模板
                    eachTable(rows, textMap, prefixStr, isSymbol);
                }
            }
        }
    }

    /**
     * 遍历表格
     *
     * @param rows    表格行对象
     * @param textMap 需要替换的信息集合
     */
    public static void eachTable(List<XWPFTableRow> rows, Map<String, String> textMap, String prefixStr,
            boolean isSymbol) {
        for (XWPFTableRow row : rows) {
            List<XWPFTableCell> cells = row.getTableCells();
            for (XWPFTableCell cell : cells) {
                // 判断单元格内容是否可以替换
                String cellText = cell.getText();
                if (StringUtils.isNotBlank(cellText) && cellText.contains(prefixStr)) {
                    List<XWPFParagraph> paragraphs = cell.getParagraphs();
                    for (XWPFParagraph paragraph : paragraphs) {
                        String pgText = paragraph.getText();
                        if (StringUtils.isNotBlank(pgText) && pgText.contains(prefixStr)) {
                            if (isSymbol) {
                                replaceSymbol(textMap, paragraph, prefixStr);
                            } else {
                                replaceText(textMap, paragraph);
                            }
                        }
                    }
                }
            }
        }
    }

    private static void replaceSymbol(Map<String, String> textMap, XWPFParagraph paragraph, String prefixStr) {
        List<XWPFRun> runs = paragraph.getRuns();
        List<Integer> removeList = new ArrayList<Integer>();
        if (CollectionUtils.isNotEmpty(runs)) {
            int index = 0;
            String key = "";
            boolean start = false;
            for (XWPFRun run : runs) {
                String text = run.toString();
                if (text.contains(prefixStr)) {
                    if (text.startsWith("${")) {
                        start = true;
                        key = key + text;
                        run.setText("", 0);
                    }
                    if (text.endsWith("@")) {
                        // 关键字没有被拆分
                        start = false;
                        run.setText("", 0);
                        String value = textMap.get(key);
                        if ("1".equals(value)) {
                            removeList.add(index + 1);
                        } else {
                            removeList.add(index + 2);
                        }
                    }
                }
                if (start && text.endsWith("@")) {
                    // 关键字补拆分了
                    start = false;
                    key = key + text;
                    run.setText("", 0);
                    String value = textMap.get(key);
                    if ("1".equals(value)) {
                        removeList.add(index + 1);
                    } else {
                        removeList.add(index + 2);
                    }
                } else if (start && !text.startsWith("${")) {
                    // 关键字补拆分了，中间的字符
                    key = key + text;
                    run.setText("", 0);
                }
                index++;
            }
        }

        int count = 0;
        for (int i : removeList) {
            int a = i - count;
            paragraph.removeRun(a);
            count++;
        }
    }

    private static void replaceText(Map<String, String> textMap, XWPFParagraph paragraph) {
        List<XWPFRun> runs = paragraph.getRuns();
        StringBuffer runTextSb = new StringBuffer();
        if (CollectionUtils.isNotEmpty(runs)) {
            XWPFRun first = runs.get(0);
            for (XWPFRun run : runs) {
                runTextSb.append(run.toString());
                run.setText("", 0);
            }
            String runText = changeValue(runTextSb.toString(), textMap);
            first.setText(runText, 0);
        }
    }

    /**
     * 匹配传入信息集合与模板
     *
     * @param value   模板需要替换的区域
     * @param textMap 传入信息集合
     * @return 模板需要替换区域信息集合对应值
     */
    public static String changeValue(String value, Map<String, String> textMap) {
        Set<Entry<String, String>> textSets = textMap.entrySet();
        for (Entry<String, String> textSet : textSets) {
            // 匹配模板与替换值 格式${key}
            String key = textSet.getKey();
            String replaceVal = textSet.getValue() == null ? "" : textSet.getValue();
            if (value.indexOf(key) != -1) {
                value = value.replace(key, replaceVal);
            }
        }
        return value;
    }

    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("1");
        list.add("2");
        list.remove(1);
    }

}